import React, { useState } from 'react'
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Typography, 
  Space, 
  Alert, 
  Select,
  Row,
  Col,
  Progress,
  Checkbox,
} from 'antd'
import { 
  UserOutlined, 
  LockOutlined, 
  MailOutlined,
  UserAddOutlined,
  ArrowLeftOutlined,
  SafetyOutlined,
} from '@ant-design/icons'
import { useNavigate, Link } from 'react-router-dom'
import { useMutation } from 'react-query'
import { authApi, UserRegister } from '../services/auth'

const { Title, Text, Paragraph } = Typography
const { Option } = Select

const Register: React.FC = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [passwordStrength, setPasswordStrength] = useState(0)
  const [agreedToTerms, setAgreedToTerms] = useState(false)

  // 注册mutation
  const registerMutation = useMutation(authApi.register, {
    onSuccess: () => {
      // 注册成功后跳转到登录页面
      navigate('/login', { 
        state: { 
          message: '注册成功！请使用您的账号密码登录。' 
        } 
      })
    },
    onError: (error: any) => {
      console.error('注册失败:', error)
    },
  })

  // 处理注册
  const handleRegister = async (values: UserRegister) => {
    if (!agreedToTerms) {
      return
    }
    await registerMutation.mutateAsync(values)
  }

  // 检查密码强度
  const checkPasswordStrength = (password: string) => {
    let strength = 0
    if (password.length >= 6) strength += 25
    if (password.length >= 8) strength += 25
    if (/[A-Z]/.test(password)) strength += 25
    if (/[0-9]/.test(password)) strength += 25
    
    setPasswordStrength(strength)
  }

  const getPasswordStrengthText = () => {
    if (passwordStrength < 25) return '弱'
    if (passwordStrength < 50) return '一般'
    if (passwordStrength < 75) return '良好'
    return '强'
  }

  const getPasswordStrengthColor = () => {
    if (passwordStrength < 25) return '#ff4d4f'
    if (passwordStrength < 50) return '#faad14'
    if (passwordStrength < 75) return '#1890ff'
    return '#52c41a'
  }

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    }}>
      <Row style={{ width: '100%', maxWidth: 1200 }}>
        <Col xs={24} md={12} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ textAlign: 'center', color: 'white', padding: '40px' }}>
            <Title level={1} style={{ color: 'white', fontSize: '3rem', marginBottom: '20px' }}>
              加入我们
            </Title>
            <Paragraph style={{ color: 'white', fontSize: '1.2rem', opacity: 0.9 }}>
              创建您的管理员账户
            </Paragraph>
            <Paragraph style={{ color: 'white', opacity: 0.8 }}>
              获得设备管理系统的完整访问权限，体验强大的分片集群管理功能
            </Paragraph>
            
            <div style={{ marginTop: '30px' }}>
              <Space direction="vertical" size="large">
                <div style={{ display: 'flex', alignItems: 'center', color: 'white' }}>
                  <SafetyOutlined style={{ fontSize: '1.5rem', marginRight: '12px' }} />
                  <Text style={{ color: 'white' }}>安全可靠的权限管理</Text>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', color: 'white' }}>
                  <UserOutlined style={{ fontSize: '1.5rem', marginRight: '12px' }} />
                  <Text style={{ color: 'white' }}>个性化的用户体验</Text>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', color: 'white' }}>
                  <MailOutlined style={{ fontSize: '1.5rem', marginRight: '12px' }} />
                  <Text style={{ color: 'white' }}>及时的系统通知</Text>
                </div>
              </Space>
            </div>
          </div>
        </Col>
        
        <Col xs={24} md={12} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Card
            style={{
              width: '100%',
              maxWidth: 450,
              boxShadow: '0 10px 30px rgba(0, 0, 0, 0.3)',
              borderRadius: '12px',
            }}
          >
            <div style={{ textAlign: 'center', marginBottom: '30px' }}>
              <Title level={2} style={{ color: '#1890ff', marginBottom: '8px' }}>
                创建新账户
              </Title>
              <Text type="secondary">请填写以下信息完成注册</Text>
            </div>

            {registerMutation.error && (
              <Alert
                message="注册失败"
                description={(registerMutation.error as any)?.message || '请检查输入信息'}
                type="error"
                style={{ marginBottom: '20px' }}
                showIcon
              />
            )}

            <Form
              form={form}
              name="register"
              onFinish={handleRegister}
              layout="vertical"
              size="large"
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名!' },
                  { min: 3, message: '用户名至少3个字符!' },
                  { max: 20, message: '用户名最多20个字符!' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线!' },
                ]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="输入用户名"
                  allowClear
                />
              </Form.Item>

              <Form.Item
                name="email"
                label="邮箱地址"
                rules={[
                  { required: true, message: '请输入邮箱地址!' },
                  { type: 'email', message: '请输入有效的邮箱地址!' },
                ]}
              >
                <Input
                  prefix={<MailOutlined />}
                  placeholder="输入邮箱地址"
                  allowClear
                />
              </Form.Item>

              <Form.Item
                name="full_name"
                label="姓名"
                rules={[
                  { max: 50, message: '姓名最多50个字符!' },
                ]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="输入真实姓名（可选）"
                  allowClear
                />
              </Form.Item>

              <Form.Item
                name="role"
                label="用户角色"
                initialValue="viewer"
                rules={[
                  { required: true, message: '请选择用户角色!' },
                ]}
              >
                <Select placeholder="选择用户角色">
                  <Option value="viewer">查看者</Option>
                  <Option value="operator">操作员</Option>
                  <Option value="admin">管理员</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码!' },
                  { min: 6, message: '密码至少6个字符!' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="输入密码"
                  allowClear
                  onChange={(e) => checkPasswordStrength(e.target.value)}
                />
              </Form.Item>

              {passwordStrength > 0 && (
                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    密码强度: {getPasswordStrengthText()}
                  </Text>
                  <Progress
                    percent={passwordStrength}
                    strokeColor={getPasswordStrengthColor()}
                    showInfo={false}
                    size="small"
                    style={{ marginTop: '4px' }}
                  />
                </div>
              )}

              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码!' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve()
                      }
                      return Promise.reject(new Error('两次输入的密码不一致!'))
                    },
                  }),
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="再次输入密码"
                  allowClear
                />
              </Form.Item>

              <Form.Item>
                <Checkbox 
                  checked={agreedToTerms} 
                  onChange={(e) => setAgreedToTerms(e.target.checked)}
                  style={{ fontSize: '12px' }}
                >
                  我已阅读并同意 
                  <Link to="/terms" target="_blank"> 服务条款 </Link>
                  和
                  <Link to="/privacy" target="_blank"> 隐私政策</Link>
                </Checkbox>
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={registerMutation.isLoading}
                  icon={<UserAddOutlined />}
                  disabled={!agreedToTerms}
                  block
                  style={{ height: '45px', fontSize: '16px' }}
                >
                  创建账户
                </Button>
              </Form.Item>
            </Form>

            <div style={{ textAlign: 'center', marginTop: '20px' }}>
              <Link to="/login" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#1890ff' }}>
                <ArrowLeftOutlined style={{ marginRight: '8px' }} />
                已有账户？立即登录
              </Link>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default Register